package tags.templates;

import java.text.SimpleDateFormat;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import main.PMF;
import main.UserView;

import DBClasses.NewsLetter;
import DBClasses.User;

public class NewsTag extends TagSupport
{
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	public int doStartTag() throws JspException
	{
		String result = "";
		PersistenceManager manager = PMF.get().getPersistenceManager();
		List<NewsLetter> news = null;
		try
		{
			news = (List<NewsLetter>) manager.newQuery(
					"select from " + NewsLetter.class.getName()).execute();
		} catch (Exception ex)
		{
		}
		UserView uv = (UserView) ((HttpServletRequest) pageContext.getRequest())
				.getSession().getAttribute("user");
		User usr = null;
		if (uv != null)
			usr = uv.getUser();
		if (news != null && news.size() > 0)
		{
			for (NewsLetter newsLetter : news)
			{
				Long id = 0L;
				try
				{
					id = Long.parseLong(newsLetter.getImg());
				} catch (Exception ex)
				{
					id = 0L;
				}
				SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm");
				String lastres = result;
				result = "<div class=\"news_block\">";
				if (id > 0)
					result += "<img alt=\"\" src=\"/egs_img?max=300&img_id="
							+ newsLetter.getImg() + "\" class=\"news_icon\" />";
				result += "<div class=\"news_header\">" + newsLetter.getTitle()
						+ "<div class=\"news_inf\">"
						+ sdf.format(newsLetter.getPostDate()) + ", "
						+ newsLetter.getAuthor() + "</div></div>"
						+ newsLetter.getText();
				if (usr != null && usr.haveNewsAccess())
					result += "<input type=\"submit\" value=\"Удалить\" onclick=\"DeleteNews("
							+ newsLetter.getId() + ");\">";
				result += "</div>" + lastres;
			}
		} else
		{
			result = "<div style=\"margin:20px\">Новостей пока нет...</div>";
		}
		try
		{
			pageContext.getOut().flush();
			pageContext.getOut().print(result);
		} catch (Exception ex)
		{
			throw new JspException(ex.getMessage());
		}
		manager.close();
		return SKIP_BODY;
	}

	public void release()
	{
	}
}
